from django.db import models
from django.conf import settings
from django.core.validators import MinValueValidator, MaxValueValidator


class Questionnaire(models.Model):
    """问卷表"""
    name = models.CharField(max_length=200, verbose_name="问卷名称")
    question_id = models.CharField(max_length=200, verbose_name="问卷ID")
    description = models.TextField(blank=True, verbose_name="问卷描述")
    sub_description = models.TextField(blank=True, verbose_name="问卷二级标题")
    person = models.CharField(max_length=100, verbose_name="面向人群")
    duration = models.CharField(max_length=100, verbose_name="问卷持续时间")
    difficulty = models.CharField(max_length=100, verbose_name="问卷难易")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'questionnaire'
        verbose_name = "问卷"
        verbose_name_plural = "问卷"

    def __str__(self):
        return self.name


class Dimension(models.Model):
    """维度表"""
    questionnaire = models.ForeignKey(
        Questionnaire,
        on_delete=models.CASCADE,
        related_name='dimensions',
        verbose_name="所属问卷"
    )
    name = models.CharField(max_length=100, verbose_name="维度名称")
    description = models.TextField(blank=True, verbose_name="维度描述")
    help = models.TextField(blank=True, verbose_name="维度帮助介绍")
    list = models.JSONField(
        blank=True,
        null=True,
        verbose_name="维度列表",
        help_text="存储维度列表，如: [1,3,4,5,6]"
    )
    weight = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=1.0,
        verbose_name="权重"
    )
    # 后面添加
    # max_score = models.IntegerField(default=100, verbose_name="维度满分")

    class Meta:
        db_table = 'dimension'
        verbose_name = "维度"
        verbose_name_plural = "维度"
        ordering = ['questionnaire']
        unique_together = ['questionnaire', 'name']

    def __str__(self):
        return f"{self.questionnaire.name} - {self.name}"


class Question(models.Model):
    """问题表"""
    QUESTION_TYPES = [
        ('single', '单选题'),
        ('multiple', '多选题'),
        ('text', '文本题'),
        ('rating', '评分题'),
        ('likert', '李克特量表'),
    ]

    questionnaire = models.ForeignKey(
        Questionnaire,
        on_delete=models.CASCADE,
        related_name='questions',
        verbose_name="所属问卷"
    )
    dimension = models.ForeignKey(
        Dimension,
        on_delete=models.CASCADE,
        related_name='questions',
        verbose_name="所属维度"
    )
    title = models.TextField(verbose_name="问题标题")
    question_type = models.CharField(
        max_length=20,
        choices=QUESTION_TYPES,
        verbose_name="问题类型"
    )
    options = models.JSONField(
        blank=True,
        null=True,
        verbose_name="选项配置",
        help_text="存储选项及其分值，如: [{'text': '几乎从不', 'score': 2}, {'text': '有时', 'score': 1}, {'text': '经常', 'score': 0}]"
    )
    # 后面添加
    # max_score = models.IntegerField(default=5, verbose_name="问题满分")
    is_required = models.BooleanField(default=True, verbose_name="是否必答")
    order = models.IntegerField(default=0, verbose_name="排序")

    class Meta:
        db_table = 'question'
        verbose_name = "问题"
        verbose_name_plural = "问题"
        ordering = ['questionnaire', 'dimension', 'order']

    def __str__(self):
        return f"{self.questionnaire.name} - {self.title[:50]}"


class UserQuestionnaire(models.Model):
    """用户问卷记录表"""
    STATUS_CHOICES = [
        ('not_started', '未开始'),
        ('in_progress', '进行中'),
        ('completed', '已完成'),
        ('abandoned', '已放弃'),
    ]

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,  # 跨 app 引用
        on_delete=models.CASCADE,
        related_name='questionnaires',
        verbose_name="用户"
    )
    questionnaire = models.ForeignKey(
        Questionnaire,
        on_delete=models.CASCADE,
        related_name='user_records',
        verbose_name="问卷"
    )
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='not_started',
        verbose_name="状态"
    )
    total_score = models.IntegerField(
        default=0,
        verbose_name="总分"
    )
    percentage = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=0,
        verbose_name="得分率"
    )
    started_at = models.DateTimeField(null=True, blank=True, verbose_name="开始时间")
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name="完成时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'user_questionnaire'
        verbose_name = "用户问卷记录"
        verbose_name_plural = "用户问卷记录"
        unique_together = ['user', 'questionnaire']

    def __str__(self):
        return f"{self.user.username} - {self.questionnaire.name}"

class UserQuestionnaireReport(models.Model):
    user_questionnaire = models.OneToOneField(
        UserQuestionnaire,
        on_delete=models.CASCADE,
        related_name="report",
        verbose_name="关联问卷记录"
    )
    file = models.FileField(
        upload_to="questionnaire_reports/",
        verbose_name="报告文件"
    )
    report_type = models.CharField(
        max_length=10,
        choices=[('pdf', 'PDF'), ('word', 'Word')],
        default='word',
        verbose_name="报告类型"
    )
    generated_at = models.DateTimeField(auto_now_add=True, verbose_name="生成时间")


class UserDimensionScore(models.Model):
    """用户维度分数表"""
    user_questionnaire = models.ForeignKey(
        UserQuestionnaire,
        on_delete=models.CASCADE,
        related_name='dimension_scores',
        verbose_name="用户问卷记录"
    )
    dimension = models.ForeignKey(
        Dimension,
        on_delete=models.CASCADE,
        related_name='user_scores',
        verbose_name="维度"
    )
    score = models.IntegerField(
        default=0,
        verbose_name="维度得分"
    )
    percentage = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=0,
        verbose_name="维度得分率"
    )

    class Meta:
        db_table = 'user_dimension_score'
        verbose_name = "用户维度分数"
        verbose_name_plural = "用户维度分数"
        unique_together = ['user_questionnaire', 'dimension']

    def __str__(self):
        return f"{self.user_questionnaire.user.username} - {self.dimension.name}: {self.score}"


class UserAnswer(models.Model):
    """用户答案表"""
    user_questionnaire = models.ForeignKey(
        UserQuestionnaire,
        on_delete=models.CASCADE,
        related_name='answers',
        verbose_name="用户问卷记录"
    )
    question = models.ForeignKey(
        Question,
        on_delete=models.CASCADE,
        related_name='user_answers',
        verbose_name="问题"
    )
    answer_text = models.TextField(blank=True, verbose_name="文本答案")
    answer_options = models.JSONField(
        blank=True,
        null=True,
        verbose_name="选项答案",
        help_text="存储选中的选项，如: ['option1', 'option2'] 或 'option1'"
    )
    score = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0,
        verbose_name="问题得分"
    )
    answered_at = models.DateTimeField(auto_now_add=True, verbose_name="答题时间")

    class Meta:
        db_table = 'user_answer'
        verbose_name = "用户答案"
        verbose_name_plural = "用户答案"
        unique_together = ['user_questionnaire', 'question']

    def __str__(self):
        return f"{self.user_questionnaire.user.username} - {self.question.title[:30]}"


